import axios from 'axios'
import util from '@util'

const serverDomain = 'http://localhost:8080'

function apiUrlConcat (api) {
  return serverDomain + api
}

// http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers = {
      'Content-Type': 'application/json',
      'token': util.getItem('$xj_token')
    }
    config.data = JSON.stringify(config.data)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

export function get (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(apiUrlConcat(url), params)
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(apiUrlConcat(url), data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}
